// Generate a menu assigned to the thumbnail clicked.
function generate_menu(json) {

	var menuSelect = '';
	var box = '';
	var elements = '';
	var i = 0;

	var description = json.description;
	if((description != '') && (typeof description != 'undefined')) {
		menuSelect += '<div class="videoDescrition">' + description + '</div>';
	}
	
	if((json.menus != '') && (typeof json.menus != 'undefined')) {

		$.each(json.menus, function (key, menu) {
					
			var menuName = menu.name;
			var title = '';
			if(typeof (totalname = menu.totalName) != 'undefined') {
				title = ' title="'+ totalname +'"';
			}
			
			if((menuName != '') && (typeof menuName != 'undefined')) {
				box = '<div class="cssmenu"><ul>';
				box += '<li class="has-sub box"><a><span'+ title +' onclick="$(\'#box_'+ i +'\').toggle();">'+ menuName +'</span></a>';
				
				var empty = true; 
				elements = '<ul style="display: block;">';

				var menuCluster = menu.cluster;
									
					if((menuCluster != '') && (typeof menuCluster != 'undefined')) {
						empty = false; // The box contains at least one element
						
						elements += '<select id="box_'+ i +'" class="k-value" onchange="change_video(this)" style="display: none;"><option>Fragments</option>';
						i++;
						$.each(menu.cluster, function (key, clt) {
							elements += '<option value="'+ clt.src +'">'+ clt.k +'</option>';
							
						});
						
						elements += '</select>';
						
					}
				
				box += elements +"</ul></li></ul></div>";
				if(!empty) {
					menuSelect += box;
				}
	
			}
			
		});
	
		var videoWidth = $('#videoPlayer').attr('width').replace('px', '');
		menuSelect = $('<div id="menuSelect" style="max-width:'+ videoWidth +'px;">'+ menuSelect +'</div>');
		
	} else {
		menuSelect = $('<div id="menuSelect"></div>');
	}
	
	$('#menuSelect').replaceWith(menuSelect);
}

// Change the video and rebuild the slider with thumbs corresponding to the new video
function change_video(select) {

	var src = $(select).val(); // New video (the one that has been selected il the list)

	if (src != '') {

		if (mediaElementJS.paused == false) {
			mediaElementJS.pause();
			$(".mejs-playpause-button").toggleClass('mejs-pause mejs-play');
		}

		parentVideoSrc.push(mediaElementJS.src);
		mediaElementJS.setSrc(src);

		var ressourceURL = $('#ressourceURL').attr("value");

		$.ajax({
			type : "GET",
			url : ressourceURL,
			data : {
				"reqType" : "getJsonVideo",
				"src" : src
			},
			dataType : "json",
			success : function(jsonVideo) { // jsonVideo contains informations about the video that has been selected
				$('#buttonParentVideo').show();
				$('#menuSelect').replaceWith('<div id="menuSelect"></div>'); // Clean the old menu
				load_slider(jsonVideo); // Rebuild the slider with informations corresponding to the new video
			}
		});
	}

}
